
#include "tinyxml2.h"
#include "HTTPGet.hpp"
#include "XMLDiscover.hpp"



XMLDiscover::XMLDiscover()
{
  this->lastGetValid = false;
}



bool XMLDiscover::fetchPage(std::string targetURL)
{
  HTTPGet httpGet;
  this->strURL  = targetURL;
  this->lastGetValid = httpGet.getDocument(this->strURL, this->strXML);
  
  return (this->lastGetValid);    
}



bool XMLDiscover::parseXMLData()
{
  this->vecNames.clear();
  
  // Cannot parse data unless the last Get was successful.
  if (this->wasLastGetValid() == false) { return false; }
  
  // Parse and test for errors
  tinyxml2::XMLDocument doc;
  tinyxml2::XMLError parseError = doc.Parse( this->strXML.c_str() );
  if (parseError != tinyxml2::XML_NO_ERROR) { return false; }
  
  // Find first result in XML
  tinyxml2::XMLHandle docHandle(&doc);
  tinyxml2::XMLElement* firstResult = docHandle.FirstChildElement("query").FirstChildElement("results").FirstChildElement("quote").ToElement();
  if (!firstResult) { return false; }      
  
  // Scan through each item and discover the field names
  for (tinyxml2::XMLElement* item = firstResult->FirstChild()->ToElement(); item; item = item->NextSiblingElement()) 
  {
    vecNames.push_back(item->Name());
  }
  
  return true;   
}


bool XMLDiscover::buildSQLCreateTable()
{
  if (this->vecNames.empty()) { return false; }
  
  this->strSQLCreateTable = "CREATE TABLE IF NOT EXISTS `tableName` (\n"
			    " `myIndex` int(11) NOT NULL,\n" 
			    " `symbol` varchar(10) NOT NULL,\n";
  
  for (unsigned int idx = 0; idx < this->vecNames.size(); ++idx)
  {
    // The XML data also contains a "Symbol", ignore it, we are keeping track of symbol ourself
    if (vecNames[idx] == std::string("Symbol")) { continue; }
    
    FieldName         fieldName = this->fieldNameLookup.StringToFieldName(vecNames[idx]);
    FieldNameType fieldNameType = this->fieldNameLookup.FieldNameToFieldNameType(fieldName);
    
    this->strSQLCreateTable += std::string("`") + vecNames[idx] + std::string("`");
    if (fieldNameType == FieldNameType::Double)
    {
      this->strSQLCreateTable += " double DEFAULT NULL";
    } 
    else if (fieldNameType == FieldNameType::Int64)
    {
      this->strSQLCreateTable += " bigint(20) DEFAULT NULL";
    }
    else if (fieldNameType == FieldNameType::Date) 
    {
      this->strSQLCreateTable += " date DEFAULT NULL";
    } 
    else if (fieldNameType == FieldNameType::DateTime)
    {
      this->strSQLCreateTable += " datetime DEFAULT NULL";
    }
    else 
    {
      this->strSQLCreateTable += " text";
    }
    // Add a comma to all but the last one
    if (idx < this->vecNames.size() - 1) {
      this->strSQLCreateTable += ",\n";
    } else {
      this->strSQLCreateTable += "\n";
    }
    
    
  } // for vecNames
  
  this->strSQLCreateTable += ") ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;\n\n";
  
  this->strSQLCreateTable += "ALTER TABLE `tableName`\n";
  this->strSQLCreateTable += " ADD PRIMARY KEY (`myIndex`), ADD UNIQUE KEY `symbol` (`symbol`), ADD KEY `myIndex` (`myIndex`);\n\n";
  
  this->strSQLCreateTable += "ALTER TABLE `tableName`\n";
  this->strSQLCreateTable += "MODIFY `myIndex` int(11) NOT NULL AUTO_INCREMENT;\n\n";
  
  return true;
}



